import service from '@/api/service'

const state = {
    autoSelectData: {},
    autoCascaderData: {}
}
const getters = {};
const mutations = {
    //单选公用
    getAutoSelectData(state, payload) {
        state.autoSelectData = {...state.autoSelectData, [payload.dataType]: payload.data}
    },
    //级联公用
    getAutoCascaderData(state, payload) {
        state.autoCascaderData = {...state.autoCascaderData, [payload.dataType]: payload.data}
    }
};
const actions = {
    // 单选公用
    async getAutoSelectData({commit}, params) {
        switch (params.dataType) {
            //角色
            case 'role':
                const role = await service.searchRoles({
                    pageNum: 1,
                    pageSize: 1000
                });
                if (role.status < 400 && role.res.result) {
                    commit("getAutoSelectData", {
                        dataType: params.dataType,
                        data: mapSelectData(role.res.result)
                    })
                }
                break;
            //部门
            case 'dept':
                const dept = await service.searchDepts({
                    pageNum: 1,
                    pageSize: 1000
                });
                if (dept.status < 400 && dept.res.result) {
                    commit("getAutoSelectData", {
                        dataType: params.dataType,
                        data: mapSelectData(dept.res.result)
                    })
                }
                break;
            default:
                break;
        }
    },
    // 级联公用
    async getAutoCascaderData({commit}, params) {
        switch (params.dataType) {
            //菜单
            case 'menu':
                const menu = await service.getMenuTree({});
                if (menu.status < 400 && menu.res) {
                    commit('getAutoCascaderData', {
                        dataType: params.dataType,
                        data: mapMenuData(menu.res)
                    })
                }
                break;
            default:
                break;
        }
    }
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}

const mapMenuData = data => {
    return data ? data.map(item => {
        return {
            value: item.id,
            label: item.name,
            children: mapMenuData(item.subMenus)
        }
    }) : data
};

const mapSelectData = (data) => {
    return data ? data.map(item => {
        return {
            value: String(item.id),
            label: item.name
        }
    }) : null
};